//
//  QLCircleOfFriendsVC.m
//  神约
//
//  Created by qlwl on 16/12/14.
//  Copyright © 2016年 qlwl. All rights reserved.
//

#import "QLCircleOfFriendsVC.h"
#import "QLCircleOfFriendsCell.h"
#import "UIView+FrameKIt.h"
#import "ChatKeyBoard.h"
#import "FaceSourceManager.h"
#import "UIAlertController+AlertController.h"
#import "QLPublishCircleFriendsVC.h"
#import "QLCircleOfFriendsLisModel.h"
#import <MediaPlayer/MediaPlayer.h>
#import "NSDate+time.h"
#import "NSString+time.h"
#import "UIBarButtonItem+Extension.h"
#import "WYVideoCompressTools.h"
#import <AVFoundation/AVFoundation.h>
#import "JRMenuView.h"
#import <RegexKitLite.h>

@interface QLCircleOfFriendsVC ()<ChatKeyBoardDelegate, ChatKeyBoardDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) ChatKeyBoard *chatKeyBoard;
@property (nonatomic, assign) CGFloat history_Y_offset;//记录table的offset.y
@property (nonatomic, assign) CGFloat seletedCellHeight;//记录点击cell的高度，高度由代理传过来


@property (nonatomic, assign) BOOL needUpdateOffset;//控制是否刷新table的offset

@property (nonatomic,copy)NSIndexPath *currentIndexPath;
@property (nonatomic, copy) NSIndexPath * commentIndex ;

@end

@implementation QLCircleOfFriendsVC
{
    float _cellHeight;
    NSMutableArray * _dataArray;
    int _page;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if ([super initWithCoder:aDecoder]) {
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self setNavTitle:@"动态"];
    [self getRightBar];
    [self setNavBarColor:NavBarTintColor];
    [self chatKeyBoard];
    _page = 1;
    _dataArray = [[NSMutableArray alloc] init];
    self.tableView.mj_header = [QL_MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self netWorkingWithPage:_page];
    }];
    self.tableView.mj_footer = [QL_MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self netWorkingWithPage:_page];
    }];
    
    [SVProgressHUD QLShowWithMaskType:SVProgressHUDMaskTypeClear];
    [self netWorkingWithPage:_page];
}
- (void)getRightBar
{
    UIBarButtonItem *barItem = [UIBarButtonItem itemWithTitle:nil norImage:@"circleOfFriTakePhoto" higImage:nil tagert:self action:@selector(barBtnClick:)];
    barItem.customView.tag = 3;
    self.navigationItem.rightBarButtonItems = @[barItem];
}
- (void)barBtnClick:(UIButton *)btn
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet andCancelAction:^{
        
    } andOtherAction:^(int tag) {
        [self selectImaWithType:PickerVideoSourceType + tag];
    } cancelButtonTitle:@"取消" otherButtonTitles:@"小视频",@"拍照",@"从手机相册选择",nil];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    //注册键盘出现NSNotification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    //注册键盘隐藏NSNotification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark keyBoard
- (NSArray<ChatToolBarItem *> *)chatKeyBoardToolbarItems
{
    ChatToolBarItem *item1 = [ChatToolBarItem barItemWithKind:kBarItemFace normal:@"face" high:@"face_HL" select:@"keyboard"];
    
    //    ChatToolBarItem *item2 = [ChatToolBarItem barItemWithKind:kBarItemVoice normal:@"voice" high:@"voice_HL" select:@"keyboard"];
    //
    //    ChatToolBarItem *item3 = [ChatToolBarItem barItemWithKind:kBarItemMore normal:@"more_ios" high:@"more_ios_HL" select:nil];
    //
    //    ChatToolBarItem *item4 = [ChatToolBarItem barItemWithKind:kBarItemSwitchBar normal:@"switchDown" high:nil select:nil];
    return @[item1];
    //    return @[item1, item2, item3, item4];
}

- (NSArray<FaceThemeModel *> *)chatKeyBoardFacePanelSubjectItems
{
    return [FaceSourceManager loadFaceSource];
}

-(ChatKeyBoard *)chatKeyBoard{
    if (_chatKeyBoard==nil) {
        _chatKeyBoard =[ChatKeyBoard keyBoardWithNavgationBarTranslucent:NO];
        _chatKeyBoard.delegate = self;
        _chatKeyBoard.dataSource = self;
        _chatKeyBoard.keyBoardStyle = KeyBoardStyleComment;
        _chatKeyBoard.allowFace = NO;
        _chatKeyBoard.allowVoice = NO;
        _chatKeyBoard.allowMore = NO;
        _chatKeyBoard.allowSwitchBar = NO;
        _chatKeyBoard.placeHolder = @"评论";
        [self.view addSubview:_chatKeyBoard];
        [self.view bringSubviewToFront:_chatKeyBoard];
    }
    return _chatKeyBoard;
}
- (void)chatKeyBoardSendText:(NSString *)text{
    
    [self saveCommentNetWithContent:text andListIndex:self.currentIndexPath andCommentIndex:self.commentIndex];
    [self keyboardDownForComment];
    self.chatKeyBoard.placeHolder = nil;
}
- (void)chatKeyBoardFacePicked:(ChatKeyBoard *)chatKeyBoard faceStyle:(NSInteger)faceStyle faceName:(NSString *)faceName delete:(BOOL)isDeleteKey{
    NSLog(@"%@",faceName);
}
- (void)chatKeyBoardAddFaceSubject:(ChatKeyBoard *)chatKeyBoard{
    NSLog(@"%@",chatKeyBoard);
}
- (void)chatKeyBoardSetFaceSubject:(ChatKeyBoard *)chatKeyBoard{
    NSLog(@"%@",chatKeyBoard);
    
}
#pragma mark keyboardWillShow
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    __block  CGFloat keyboardHeight = [aValue CGRectValue].size.height;
    if (keyboardHeight==0) {//解决搜狗输入法三次调用此方法的bug、
        //        IOS8.0之后可以安装第三方键盘，如搜狗输入法之类的。
        //        获得的高度都为0.这是因为键盘弹出的方法:- (void)keyBoardWillShow:(NSNotification *)notification需要执行三次,你如果打印一下,你会发现键盘高度为:第一次:0;第二次:216:第三次:282.并不是获取不到高度,而是第三次才获取真正的高度.
        return;
    }
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.view.bounds;
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    CGFloat delta = 0.0;
    if (self.seletedCellHeight){//点击某行，进行回复某人
        delta = self.history_Y_offset - ([UIApplication sharedApplication].keyWindow.bounds.size.height - keyboardHeight-self.seletedCellHeight-kChatToolBarHeight);
    }else{//点击评论按钮
        delta = self.history_Y_offset - ([UIApplication sharedApplication].keyWindow.bounds.size.height - keyboardHeight-kChatToolBarHeight);//24为评论按钮高度，10为评论按钮上部的5加评论按钮下部的5
    }
    CGPoint offset = self.tableView.contentOffset;
    offset.y += delta;
    if (offset.y < 0) {
        offset.y = 0;
    }
    if (self.needUpdateOffset) {
        [self.tableView setContentOffset:offset animated:YES];
    }
    
}
#pragma mark keyboardWillHide
- (void)keyboardWillHide:(NSNotification *)notification {
    //    NSValue *animationDurationValue = [notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    //    NSTimeInterval animationDuration;
    //    [animationDurationValue getValue:&animationDuration];
    //    [UIView animateWithDuration:animationDuration animations:^{
    //    }];
    self.needUpdateOffset = NO;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (_chatKeyBoard) {
        [self keyboardDownForComment];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"CommentViewController didReceiveMemoryWarning");
    
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [self keyboardDownForComment];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"CommentViewController dealloc");
}
- (void)keyboardDownForComment
{
    [self.chatKeyBoard keyboardDownForComment];
    self.currentIndexPath = nil;
    self.commentIndex = nil;
}


#pragma mark TabDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellName = @"cellName";
    QLCircleOfFriendsCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[QLCircleOfFriendsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellName];
    }
    QLCircleOfFriendsLisModel * model = _dataArray[indexPath.row];
    
    [cell.userHead QL_setImageWithURL:[NSString stringWithFormat:@"%@%@",HTTP_BaseURL,model.headpicurl] placeholderImage:UserHeadDefaultIma];
    cell.nameLab.text = model.username;
    cell.sexIma.image = [UIImage imageNamed:@"circleSexOfMan"];
    cell.contentLab.text = model.content;
    if (model.resouceType == ResouceOfPic) {
        cell.ImaBgView.resoucType = ResouceOfPic;
        cell.ImaBgView.imaItemArray = model.pic;
    }else if(model.resouceType == ResouceOfVideo){
        cell.ImaBgView.resoucType = ResouceOfVideo;
        cell.ImaBgView.imaItemArray = model.videos;
    }else {
        cell.ImaBgView.imaItemArray = nil;
    }
    if (model.latitude.length>0 && model.longitude.length>0) {
        cell.addressLab.textContainer = [self creatTextContainerWithAddress:model.address];
    }else{
        cell.addressLab.textContainer = nil;
    }
    cell.timeLab.text = [QLCircleOfFriendsLisModel showTime:[[model.createtime dateFromStringWithFormat:@"YYYY-MM-dd HH:mm:ss"] timeIntervalSince1970] showDetail:YES];
//    cell.priseLab.text = [NSString stringWithFormat:@"%d",model.heartnums];
    cell.commentView.commentArray = [self getCommentListWithComments:model.comments];
    cell.commentView.prisePeople = [self getPrisePeople:model.praises];
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    __weak __typeof(self) weakSelf= self;
    __weak __typeof(window) weakWindow= window;
//    cell.commentBtnClick = ^(QLCircleOfFriendsCell * cell){
//        //不是点击cell进行回复，则置空replayTheSeletedCellModel，因为这个时候是点击评论按钮进行评论，不是回复某某某
//        weakSelf.needUpdateOffset = YES;
//        weakSelf.chatKeyBoard.placeHolder = [NSString stringWithFormat:@"评论 %@",model.username];
//        weakSelf.history_Y_offset = [cell convertRect:cell.bounds toView:weakWindow].origin.y + cell.f_height;
//        if ([indexPath compare:weakSelf.currentIndexPath] != NSOrderedSame) {
//            if (weakSelf.currentIndexPath == nil) {
//                weakSelf.currentIndexPath = indexPath;
//                weakSelf.commentIndex = nil;
//                [weakSelf.chatKeyBoard keyboardUpforComment];
//            }else{
//                [self keyboardDownForComment];
//            }
//        }else{
//            if (self.commentIndex != nil) {
//                [self keyboardDownForComment];
//            }
//        }
//    };
    cell.commentItemClick = ^(NSIndexPath * commentIndex,float history_Y_offset){
        weakSelf.needUpdateOffset = YES;
        QLCircleOfCommentModel * replayModel = model.comments[commentIndex.row];
        QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
        if ([replayModel.createby isEqualToString:loginModel.userId]) {
            return ;
        }
        weakSelf.chatKeyBoard.placeHolder = [NSString stringWithFormat:@"回复 %@",replayModel.createbyname];
        weakSelf.history_Y_offset = history_Y_offset;
        
        if ([indexPath compare:weakSelf.currentIndexPath] != NSOrderedSame) {
            if (weakSelf.currentIndexPath == nil&& weakSelf.commentIndex == nil) {
                weakSelf.currentIndexPath = indexPath;
                weakSelf.commentIndex = commentIndex;
                [weakSelf.chatKeyBoard keyboardUpforComment];
            }else{
                [self keyboardDownForComment];
            }
        }else{
            if ([commentIndex compare:weakSelf.commentIndex] != NSOrderedSame) {
                if (weakSelf.commentIndex == nil) {
                    weakSelf.currentIndexPath = indexPath;
                    weakSelf.commentIndex = commentIndex;
                    [weakSelf.chatKeyBoard keyboardUpforComment];
                }else{
                    [self keyboardDownForComment];
                }
            }
        }
    };
    cell.showPhoto = ^(NSInteger index){
        [weakSelf keyboardDownForComment];
    };
    cell.palyVideo = ^(NSString * urlPath){
        [weakSelf keyboardDownForComment];
        [self playPlayerWithMovieStr:[NSString stringWithFormat:@"%@%@",HTTP_BaseURL,urlPath]];
    };
//    cell.sendPrise = ^{
//        //送红心
//        [self sendPriseNetWithIndex:indexPath];
//    };
    cell.CLICKMENUBLOCK = ^{
        NSArray * itemsArray = @[@"点赞",@"评论"];
        return itemsArray;
    };
    cell.CLICKITEMSBLOCK = ^(NSInteger itemIndex){
        if (itemIndex == 0) {
            //点赞
            [self priserNetWithIndex:indexPath];
        }else{
            //评论
            //不是点击cell进行回复，则置空replayTheSeletedCellModel，因为这个时候是点击评论按钮进行评论，不是回复某某某
            weakSelf.needUpdateOffset = YES;
            weakSelf.chatKeyBoard.placeHolder = [NSString stringWithFormat:@"评论 %@",model.username];
            weakSelf.history_Y_offset = [cell convertRect:cell.bounds toView:weakWindow].origin.y + cell.f_height;
            if ([indexPath compare:weakSelf.currentIndexPath] != NSOrderedSame) {
                if (weakSelf.currentIndexPath == nil) {
                    weakSelf.currentIndexPath = indexPath;
                    weakSelf.commentIndex = nil;
                    [weakSelf.chatKeyBoard keyboardUpforComment];
                }else{
                    [self keyboardDownForComment];
                }
            }else{
                if (self.commentIndex != nil) {
                    [self keyboardDownForComment];
                }
            }
        }
    };
    
    [cell refreshHeight];
    model.cellHeight = cell.f_height;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QLCircleOfFriendsLisModel * model = _dataArray[indexPath.row];
    return model.cellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)onTapTableview
{
    [JRMenuView dismissAllJRMenu];//点击tableview收回所有展开的JRMenu
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [JRMenuView dismissAllJRMenu];//滚动tableview收回所有展开的JRMenu
}
#pragma mark separat 分割线设置
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

// 播放网络视频
- (void)playPlayerWithMovieStr:(NSString *)movStr
{
    MPMoviePlayerViewController *playerVC=[[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:movStr]];
    [playerVC.moviePlayer prepareToPlay];
    [self presentViewController:playerVC animated:YES completion:nil];
}

#pragma mark textContainer

- (TYTextContainer *)creatTextContainerWithAddress:(NSString *)address
{
    NSString *text = address;
    // 属性文本生成器
    TYTextContainer *textContainer = [[TYTextContainer alloc]init];
    
    textContainer.text = text;
    
    TYTextStorage *textStorage = [[TYTextStorage alloc]init];
    textStorage.range = [text rangeOfString:text];
    textStorage.textColor = [UIColor blueColor];
    textStorage.font = [UIFont systemFontOfSize:11];
    [textContainer addTextStorage:textStorage];
    [textContainer addLinkWithLinkData:@"" linkColor:[UIColor blueColor] underLineStyle:kCTUnderlineStyleNone range:textStorage.range];
    return textContainer;
}
//循环获取评论属性字符串
- (NSMutableArray<TYTextContainer *> *)getCommentListWithComments:(NSArray<QLCircleOfCommentModel *> *)comments
{
    NSMutableArray * commentListArray = [[NSMutableArray alloc] init];
    for (QLCircleOfCommentModel * model in comments) {
        [commentListArray addObject:[self creatCommentWithCommentModel:model]];
    }
    return commentListArray;
}

- (TYTextContainer *)creatCommentWithCommentModel:(QLCircleOfCommentModel *)comment
{
    TYTextContainer *textContainer = [[TYTextContainer alloc]init];
    textContainer.textColor = [UIColor blackColor];
    textContainer.lineBreakMode = kCTLineBreakByTruncatingHead;
    textContainer.numberOfLines = 0;
    textContainer.font = [UIFont systemFontOfSize:14];
    
    if (comment.type == 2) {
        NSString * name1 = comment.createbyname;
        NSString * name2 = comment.beiusername;
        NSString * text = [name1 stringByAppendingFormat:@"回复%@：%@",name2,comment.content];
        textContainer.text = text;
        TYTextStorage *textStorage1 = [[TYTextStorage alloc]init];
        textStorage1.range = NSMakeRange(0, name1.length);
        //    NSLog(@"%lud",(unsigned long)textStorage1.range.length);
        //    textStorage1.textColor = [UIColor blueColor];
        textStorage1.font = [UIFont systemFontOfSize:14];
        [textContainer addLinkWithLinkData:@"" linkColor:[UIColor blueColor] underLineStyle:kCTUnderlineStyleNone range:textStorage1.range];
        [textContainer addTextStorage:textStorage1];
        TYTextStorage *textStorage2 = [[TYTextStorage alloc]init];
        textStorage2.range = NSMakeRange([name1 stringByAppendingString:@"回复"].length,name2.length);
        //    textStorage2.textColor = [UIColor blueColor];
        textStorage2.font = [UIFont systemFontOfSize:14];
        [textContainer addLinkWithLinkData:@"" linkColor:[UIColor blueColor] underLineStyle:kCTUnderlineStyleNone range:textStorage2.range];
        [textContainer addTextStorage:textStorage2];
    }else{
        NSString * name1 = comment.createbyname;
        NSString * text = [name1 stringByAppendingFormat:@"：%@",comment.content];
        textContainer.text = text;
        TYTextStorage *textStorage1 = [[TYTextStorage alloc]init];
        textStorage1.range = NSMakeRange(0, name1.length);
        textStorage1.font = [UIFont systemFontOfSize:14];
        [textContainer addLinkWithLinkData:@"" linkColor:[UIColor blueColor] underLineStyle:kCTUnderlineStyleNone range:textStorage1.range];
        [textContainer addTextStorage:textStorage1];
    }
    return textContainer;
}
- (TYTextContainer *)getPrisePeople:(NSArray<QLCircleOfPraiseModel *>*)praises
{
    if (praises.count>0) {
        TYTextContainer *textContainer = [[TYTextContainer alloc]init];
        textContainer.textColor = [UIColor blackColor];
        textContainer.lineBreakMode = kCTLineBreakByTruncatingHead;
        textContainer.numberOfLines = 0;
        textContainer.font = [UIFont systemFontOfSize:14];
        
        NSString * text = @"[icon_praise,15,15] ";
        for (QLCircleOfPraiseModel * praise in praises) {
            text = [text stringByAppendingString:praise.createbyname];
            text = [text stringByAppendingString:@"、"];
        }
        textContainer.text = text;
        
        NSMutableArray *tmpArray = [NSMutableArray array];
        // 正则匹配图片信息
        [text enumerateStringsMatchedByRegex:@"\\[(\\w+?),(\\d+?),(\\d+?)\\]" usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
            if (captureCount > 3) {
                // 图片信息储存
                TYImageStorage *imageStorage = [[TYImageStorage alloc]init];
                imageStorage.cacheImageOnMemory = YES;
                imageStorage.imageName = capturedStrings[1];
                imageStorage.range = capturedRanges[0];
                imageStorage.size = CGSizeMake([capturedStrings[2]intValue], [capturedStrings[3]intValue]);
                [tmpArray addObject:imageStorage];
            }
        }];
        // 添加图片信息数组到label
        [textContainer addTextStorageArray:tmpArray];
        
        text = @"[icon_praise,15,15] ";
        for (QLCircleOfPraiseModel * praise in praises) {
            TYTextStorage *textStorage1 = [[TYTextStorage alloc]init];
            textStorage1.range = NSMakeRange(text.length, praise.createbyname.length);
//            textStorage1.text = praise.createbyname;
            textStorage1.font = [UIFont systemFontOfSize:14];
            [textContainer addLinkWithLinkData:@"" linkColor:[UIColor blueColor] underLineStyle:kCTUnderlineStyleNone range:textStorage1.range];
            [textContainer addTextStorage:textStorage1];
            text = [text stringByAppendingString:praise.createbyname];
            text = [text stringByAppendingString:@"、"];
        }
        return textContainer;
    }
    return nil;
}

#pragma mark PickerController 相机相册
- (void)finishImagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info andType:(PickerControllerSourceType)type andMediaURL:(NSURL *)url
{
    if (type==PickerVideoSourceType) {
        NSString * mediaPath = [url path];
        
        [SVProgressHUD QLShowWithStatus:@"视频压缩中" maskType:SVProgressHUDMaskTypeClear];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString * mp4Path = [self changeVideoToMap4WithVideoURL:[NSURL URLWithString:mediaPath]];
            [WYVideoCompressTools compressVideoWithSourceVideoPathString:mp4Path CompressType:AVAssetExportPresetMediumQuality CompressSuccessBlock:^(NSString *compressVideoPathString) {
                if (compressVideoPathString) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSMutableArray * resouceArray = [[NSMutableArray alloc] init];
                        if(mediaPath){
                            [resouceArray addObject:compressVideoPathString];
                        }
                        QLPublishCircleFriendsVC * publishCircelVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishCircleFriendsVC" andSBName:@"Discover"];
                        publishCircelVC.resouceArray = resouceArray;
                        publishCircelVC.resouceType = PublishResouceMedia;
                        publishCircelVC.publishFinishAndRefresh = ^{
                            [self.tableView.mj_header beginRefreshing];
                        };
                        NSLog(@"%@",publishCircelVC.publishFinishAndRefresh);
                        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:publishCircelVC];
                        [picker dismissViewControllerAnimated:YES completion:^{
                            [self presentViewController:nav animated:YES completion:nil];
                        }];
                        [SVProgressHUD dismiss];
                    });
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [picker dismissViewControllerAnimated:YES completion:^{
                            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"视频压缩失败了!" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
                            UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
                            [alertController addAction:confirmAction];
                            [self presentViewController:alertController animated:YES completion:nil];
                        }];
                        [SVProgressHUD dismiss];
                    });
                    [self removeVideoWithVideoPath:mp4Path];
                }
                [self removeVideoWithVideoPath:mp4Path];
            } CompressFailedBlock:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [picker dismissViewControllerAnimated:YES completion:^{
                        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"视频压缩失败了!" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
                        [alertController addAction:confirmAction];
                        [self presentViewController:alertController animated:YES completion:nil];
                    }];
                    [SVProgressHUD dismiss];
                });
                [self removeVideoWithVideoPath:mp4Path];
            } CompressNotSupportBlock:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [picker dismissViewControllerAnimated:YES completion:^{
                        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"不支持当前压缩格式哦!" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
                        [alertController addAction:confirmAction];
                        [self presentViewController:alertController animated:YES completion:nil];
                    }];
                    [SVProgressHUD dismiss];
                });
                [self removeVideoWithVideoPath:mp4Path];
            }];
        });
    }else if (type==PickerAlbumSourceType||type==PickerCameraSourceType){
        NSMutableArray *picArray=[[NSMutableArray alloc] init];
        [picArray addObject:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
        
        QLPublishCircleFriendsVC * publishCircelVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishCircleFriendsVC" andSBName:@"Discover"];
        publishCircelVC.publishFinishAndRefresh = ^{
            [self.tableView.mj_header beginRefreshing];
        };
        publishCircelVC.resouceArray = picArray;
        publishCircelVC.resouceType = PublishResoucePic;
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:publishCircelVC];
        [picker dismissViewControllerAnimated:YES completion:^{
            [self presentViewController:nav animated:YES completion:nil];
        }];
    }
}
- (void)finishAssetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSMutableArray *)picArray
{
    //图片
    
}
- (void)failImagePickerControllerDidCancel:(UINavigationController*)picker
{
    
}
#pragma mark netWorking
- (void)netWorkingWithPage:(int)page
{
    QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"currentPage"] = [NSNumber numberWithInt:page];
    postDict[@"pageSize"] = @"30";
    postDict[@"userid"] = loginModel.userId;
    [QLNetWorking postJSONWithUrl:QLCircleOfFriendListURL parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        NSLog(@"%@",result);
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            NSMutableArray * daArray = [QLCircleOfFriendsLisModel mj_objectArrayWithKeyValuesArray:[[result objectForKey:@"mobileBody"] objectForKey:@"data"]];
            if (page == 1) {
                [_dataArray removeAllObjects];
            }
            if (daArray.count>0) {
                _page++;
                [_dataArray addObjectsFromArray:daArray];
            }
            [self.tableView reloadData];
        }
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
    } fail:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
    }];
}
- (void)saveCommentNetWithContent:(NSString *)content andListIndex:(NSIndexPath *)listIndex andCommentIndex:(NSIndexPath *)commentIndex
{
    QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
    QLCircleOfFriendsLisModel * model = _dataArray[listIndex.row];
    QLCircleOfCommentModel * commentModel = nil;
    if (self.commentIndex) {
        commentModel = model.comments[commentIndex.row];
    }
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"createby"] = loginModel.userId;
    postDict[@"beiuserid"] = commentModel?commentModel.createby:model.userid;
    postDict[@"dynamicid"] = model.id;
    postDict[@"content"] = content;
    postDict[@"type"] = commentModel?[NSNumber numberWithInt:2]:[NSNumber numberWithInt:1];
    [QLNetWorking postJSONWithUrl:QLCircleOfFriendCommentURL parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        NSLog(@"%@",result);
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            QLCircleOfCommentModel * addCommentModel = [[QLCircleOfCommentModel alloc] init];
            addCommentModel.content = content;
            addCommentModel.dynamicid = loginModel.userId;
            addCommentModel.createbyname = loginModel.name;
            addCommentModel.createby = model.userid;
            addCommentModel.beiusername = commentModel?commentModel.createbyname:model.username;
            addCommentModel.beiuserid = commentModel?commentModel.createby:model.userid;
            addCommentModel.createtime = [[NSDate date] getMyDateStrWithDateFormat:@"YYYY-MM-dd HH:mm:ss"];
            NSString * json = [[result objectForKey:@"mobileBody"] objectForKey:@"data"];
            id resultData = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            addCommentModel.dynamicCommentId = [resultData objectForKey:@"dynamicCommentId"];
            addCommentModel.type = commentIndex?2:1;
            [model.comments addObject:addCommentModel];
            [self.tableView reloadRowsAtIndexPaths:@[listIndex] withRowAnimation:UITableViewRowAnimationNone];
        }
    } fail:^(NSError *error) {
        
    }];
}
- (void)sendPriseNetWithIndex:(NSIndexPath *)index
{
    QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
    QLCircleOfFriendsLisModel * model = _dataArray[index.row];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"senduserid"] = loginModel.userId;
    postDict[@"receiveuserid"] = model.userid;
    postDict[@"giftnum"] = @"1";
    postDict[@"dynamicid"] = model.id;
    [QLNetWorking postJSONWithUrl:QLCircleSendPriseURL parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        NSLog(@"%@",result);
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            model.heartnums++;
            [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
        }else{
            [LPPopup showInCenterOfWindowWithText:[[result objectForKey:@"mobileHead"] objectForKey:@"message"] completion:nil];
        }
    } fail:^(NSError *error) {
        
    }];
}

//给某人点赞
- (void) priserNetWithIndex:(NSIndexPath *)index
{
    QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
    QLCircleOfFriendsLisModel * model = _dataArray[index.row];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"dynamicid"] = model.id;
    postDict[@"beiuserid"] = model.userid;
    postDict[@"createby"] = loginModel.userId;
    [QLNetWorking postJSONWithUrl:QLDynamicPriseURL parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            QLCircleOfPraiseModel * praise = [QLCircleOfPraiseModel mj_objectWithKeyValues:[[result objectForKey:@"mobileBody"] objectForKey:@"data"]];
            [model.praises addObject:praise];
            [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
        }
        
    } fail:^(NSError *error) {
        
    }];
    
}



@end
